package edu.hnu.cloudflight.android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSON;

import edu.hnu.cloudflight.android.domain.Flight;
import edu.hnu.cloudflight.android.domain.FlightRequest;
import edu.hnu.cloudflight.android.server.FlightDBServer;
import edu.hnu.cloudflight.android.util.DateUtil;
import edu.hnu.cloudflight.android.util.HttpUtil;
import edu.hnu.cloudflight.android.util.StringUtil;
import edu.hnu.cloudflight.android.util.ToastUtil;

public class FlightNumberResultActivity extends Activity {

	private static String TAG = "FlightNumberResultActivity";

	public static final String ACTION_FROM_COLLECT = "edu.hnu.cloudflight.android.FlightCollectActivity";
	public static final String ACTION_FROM_COURSERESULT = "edu.hnu.cloudflight.android.FlightCourseResultActivity";
	public static final String ACTION_FROM_FLIGHTNUMQUERY = "edu.hnu.cloudflight.android.FlightNumberQueryActivity";

	private ProgressDialog pd;
	private ListView resultList;

	private QueryByFlightNum task;

	private static Flight result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flight_number_result);
		resultList = (ListView) findViewById(R.id.querybyflightnumlist);

		result = null;
		Intent intent = getIntent();
		Bundle bundle = getIntent().getExtras();

		if (intent.getAction() == null || "".equals(intent.getAction()) || bundle == null) {
			new AlertDialog.Builder(this).setTitle(R.string.flightnumberresult_diag_dataerror)
					.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(getApplicationContext(), FlightActivity.class);
							startActivity(intent);
						}
					}).show();
		}

		if (ACTION_FROM_COURSERESULT.equals(intent.getAction())) {
			int position = bundle.getInt("position");
			if (position > -1) {
				Log.i(TAG, String.valueOf(position));
				Log.i(TAG, String.valueOf(MyApplication.queryByFlightCourseResult.size()));
				result = MyApplication.queryByFlightCourseResult.get(position);
				task = new QueryByFlightNum();
				task.execute("");
				return;
			}
		} else {
			String flightNum = bundle.getString("flightNum");
			Log.i(TAG, flightNum);
			String startDate;
			String endDate;
			if (ACTION_FROM_COLLECT.equals(intent.getAction())) {
				startDate = DateUtil.getNowDateToString(DateUtil.sdf1);
				endDate = startDate;
			} else {
				startDate = bundle.getString("startDate");
				endDate = bundle.getString("endDate");
			}
			pd = new ProgressDialog(this);
			pd.setTitle(R.string.flightnumberresult_diag_pleasewait);
			pd.setMessage(getResources().getString(R.string.flightnumberresult_diag_isloading));
			pd.setIndeterminate(true);
			pd.setCancelable(true);
			pd.show();
			task = new QueryByFlightNum(flightNum, startDate, endDate);
			task.execute("");
			return;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.flight, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item == null) {
			return false;
		}
		switch (item.getItemId()) {
		case R.id.flight_collect:
			if(MyApplication.appToken==null||"".equals(MyApplication.appToken)){
				ToastUtil.makeToastForShort(this, R.string.flightcollect_tos_login);
				return true;
			}
			if (result == null)
				return true;
			FlightDBServer server = FlightDBServer.getInstant(getApplicationContext());
			boolean flag = server.addFlightCollect(result);
			if (flag) {
				ToastUtil.makeToastForShort(this, "收藏成功！");
			}
			break;

		default:
			break;
		}
		return true;
	}

	private class QueryByFlightNum extends AsyncTask<String, String, Flight> {

		private final String TAG = QueryByFlightNum.class.getSimpleName();
		private String flightNum;
		private String startDate;
		@SuppressWarnings("unused")
		private String endDate;

		public QueryByFlightNum() {

		}

		public QueryByFlightNum(String flightNum, String startDate, String endDate) {
			this.flightNum = flightNum;
			this.startDate = startDate;
			this.endDate = endDate;
		}

		@Override
		protected Flight doInBackground(String... params) {
			// TODO Auto-generated method stub
			if (result != null) {
				return result;
			}
			StringBuilder sb = new StringBuilder();
			sb.append(MyApplication.queryByFlightNumUrl).append("?name=").append(flightNum).append("&date=").append(startDate).append("&key=")
					.append(MyApplication.key);
			try {
				String result = HttpUtil.getStringByGet(sb.toString());
				Log.i(TAG, result);
				FlightRequest flightRequest = JSON.parseObject(result, FlightRequest.class);
				return flightRequest.result.get(0);
			} catch (IOException e) {
				return null;
			}
		}

		protected void onPostExecute(Flight result) {
			if (pd != null) {
				pd.cancel();
			}
			if (result == null) {
				new AlertDialog.Builder(FlightNumberResultActivity.this).setTitle(R.string.flightnumberresult_diag_dataerror)
						.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(getApplicationContext(), FlightActivity.class);
								startActivity(intent);
							}
						}).show();
				return;
			} else {
				FlightNumberResultActivity.result = result;
				List<String> flightString = StringUtil.getStringFromFlight(result);
				Log.i(TAG, flightString.toString());
				List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
				for (String info : flightString) {
					Map<String, Object> temp = new HashMap<String, Object>();
					temp.put("info", info);
					data.add(temp);
				}
				SimpleAdapter flightAdapter = new SimpleAdapter(FlightNumberResultActivity.this, data, R.layout.listview_onetextview,
						new String[] { "info" }, new int[] { R.id.onetextview_info });
				resultList.setAdapter(flightAdapter);
			}
		}

	}

}
